//
//  TBQRCodeViewController.swift
//  新浪微博
//
//  Created by bin on 16/1/24.
//  Copyright © 2016年 XMG. All rights reserved.
//

import UIKit
import AVFoundation

class TBQRCodeViewController: UIViewController {

    
    @IBOutlet weak var tabBar: UITabBar!
    @IBOutlet weak var containView: UIView!
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!
    @IBOutlet weak var topConstraint: NSLayoutConstraint!
    @IBOutlet weak var QRCodeImageView: UIImageView!
    var timer: NSTimer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        containView.clipsToBounds = true
        tabBar.delegate = self
        tabBar.selectedItem = tabBar.items![0]
        setAnimation()
        
        previewLayer.frame = view.bounds
        view.layer.insertSublayer(previewLayer, atIndex: 0)
        session.startRunning()
//        timer = NSTimer(timeInterval: 0.3, target: self, selector: Selector("test"), userInfo: nil, repeats: true)
//        NSRunLoop.currentRunLoop().addTimer(timer!, forMode: NSRunLoopCommonModes)
    }
    

    
    func setAnimation(){
        topConstraint.constant = -heightConstraint.constant
        view.layoutIfNeeded()
        UIView.animateWithDuration(1.0) { () -> Void in
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.topConstraint.constant = self.heightConstraint.constant
            self.view.layoutIfNeeded()
        }

    }


    @IBAction func Close(sender: UIBarButtonItem) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    private lazy var session: AVCaptureSession = {
        
        /*
        // 1.获取捕捉会话
        AVCaptureSession *session = [[AVCaptureSession alloc] init];
        self.session = session;
        
        // 2.设置捕捉会话的输入设备
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
        [session addInput:input];
        
        // 3.设置捕捉花卉的输出设备
        AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
        [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        [session addOutput:output];
        [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
        
        // 4.添加扫描阅览的layer
        AVCaptureVideoPreviewLayer *player = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
        player.frame = self.view.bounds;
        self.layer = player;
        [self.view.layer addSublayer:player];
        */
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        let input = try? AVCaptureDeviceInput.init(device: device)
        let output = AVCaptureMetadataOutput()
        let session = AVCaptureSession()
        session.addInput(input)
        session.addOutput(output)
        output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        output.metadataObjectTypes = output.availableMetadataObjectTypes
        return session
    }()
    
    private lazy var previewLayer: AVCaptureVideoPreviewLayer = {
        let previewLayer = AVCaptureVideoPreviewLayer(session: self.session)
        return previewLayer
    }()
}

extension TBQRCodeViewController:UITabBarDelegate{
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        if item == tabBar.items![0]{
            heightConstraint.constant = 300
            QRCodeImageView.image = UIImage(named: "qrcode_scanline_barcode")
            QRCodeImageView.layer.removeAllAnimations()
            setAnimation()
            return
        }
        heightConstraint.constant = 150
        QRCodeImageView.image = UIImage(named: "qrcode_scanline_qrcode")
        QRCodeImageView.layer.removeAllAnimations()
        setAnimation()
    }
}


extension TBQRCodeViewController:AVCaptureMetadataOutputObjectsDelegate{
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
        if (metadataObjects.count > 0) {
            print("\(metadataObjects.last?.stringValue)")
        }
    }
    
}